from django.shortcuts import render,redirect
from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.form import PerttyModelForm


"""靓号"""

def pretty_list(request):
    #传查询条件显示列表
    #创建空字典
    data_dict={}
    #前端传过来的参数
    search_data=request.GET.get('q','')
    if search_data:
        #把前端传过来的参数放到字典里
        data_dict['mobile__contains']=search_data
    queryset=models.Pretty.objects.filter(**data_dict).order_by("-level")
    page_object=Pagination(request,queryset)
    form = PerttyModelForm()

    context={'form':form,
             'search_data':search_data,
             'page_queryset': page_object.page_queryset, #分完页的数据
             'page_string':page_object.html()}      #页码
    return render(request,'pretty_list.html',context)

def pretty_add(request):
    if request.method=='GET':
        form =PerttyModelForm()
        return  render(request,'pretty_add.html',{'form':form})
    form=PerttyModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request,'pretty_add.html',{'form':form})

def pretty_edit(request,nid):
    row_objet = models.Pretty.objects.filter(id=nid).first()
    if request.method=='GET':
        form = PerttyModelForm(instance=row_objet)
        return  render(request,'pretty_edit.html',{'form':form})
    form=PerttyModelForm(data=request.POST,instance=row_objet)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request,'pretty_edit.html',{'form':form})

def pretty_delete(request,nid):
    models.Pretty.objects.filter(id=nid).delete()
    return redirect('/pretty/list/')